package com.bizfx.component.mainform
{
	import flash.display.DisplayObject;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import flexlib.containers.SuperTabNavigator;
	import flexlib.controls.SuperTabBar;
	import flexlib.controls.tabBarClasses.SuperTab;
	import flexlib.events.SuperTabEvent;
	
	import com.bizfx.collections.HashMap;
	import com.bizfx.component.BizApplication;
	import com.bizfx.component.authentication.AuthenticationInfo;
	import com.bizfx.component.authentication.IAuthentication;
	import com.bizfx.component.authentication.ILoginUI;
	import com.bizfx.component.controls.CollapsibleHDividedBox;
	import com.bizfx.component.controls.DividerBox;
	import com.bizfx.component.controls.PopUpProgressBarManager;
	import com.bizfx.component.views.INavigator;
	import com.bizfx.component.views.IView;
	import com.bizfx.component.views.ViewModule;
	import com.bizfx.events.AuthenticateEvent;
	import com.bizfx.events.CommonEvent;
	import com.bizfx.events.LoginUISubmitEvent;
	import com.bizfx.events.ModuleCommandEvent;
	import com.bizfx.events.NavigatorItemEvent;
	import com.bizfx.utils.StringUtils;
	
	import mx.collections.ArrayList;
	import mx.collections.IList;
	import mx.containers.Box;
	import mx.containers.HBox;
	import mx.containers.Panel;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.core.Container;
	import mx.events.FlexEvent;
	import mx.events.ModuleEvent;
	import mx.logging.ILogger;
	import mx.logging.Log;
	import mx.modules.Module;
	import mx.modules.ModuleLoader;
	
	public class BizMainForm extends Box implements IMainForm {
		[Embed(source="../../../../assets/images/table.png")]
		private static var defaultFunctionIcon:Class;
		
		[Embed(source="../../../../assets/images/table_multiple.png")]
		private static var defaultFunctionsIcon:Class;
		
		[Embed(source="../../../../assets/images/application_home.png")]
		private static var homeIcon:Class;
		
		protected var logger:ILogger;
		
		private var _viewMap:HashMap = new HashMap();
		
		private var _viewStatuMap:HashMap = new HashMap();
		
		private var loginContainer:VBox;
		
		private var appContainer:VBox;
		
		private var dividedBox:CollapsibleHDividedBox;
		
		private var navigatorContainer:Panel;
		
		private var moduleContainer:SuperTabNavigator;
		
		private var _authentication:IAuthentication;
		
		/**
		 * 验证接口
		 */
		public function get authentication(): IAuthentication
		{
			return _authentication;  
		}
		
		public function set authentication(value: IAuthentication):void {
			_authentication = value;
		}
		
		private var _loginUI:ILoginUI;
		/**
		 * 登录界面接口
		 */
		public function get loginUI(): ILoginUI
		{
			return _loginUI;  
		}
		
		public function set loginUI(value: ILoginUI):void {
			_loginUI = value;  
		}
		
		private var _needLogin:Boolean = true;
		
		public function get needLogin():Boolean
		{
			return _needLogin;
		}
		
		public function set needLogin(value:Boolean):void
		{
			_needLogin = value;
		}
		
		private var _authenticationInfo:AuthenticationInfo;
		
		public function get authenticationInfo():AuthenticationInfo
		{
			return _authenticationInfo;
		}
		
		public function set authenticationInfo(value:AuthenticationInfo):void
		{
			_authenticationInfo = value;
		}
		
		/**
		 * 导航器接口
		 */
		private var _navigator:INavigator;
		
		public function get navigator():INavigator {
			return _navigator;
		}
		
		public function set navigator(value:INavigator):void {
			this._navigator = value;
		}
		
		private var _topBar:Container;
		
		public function get topBar():Container {
			return _topBar;
		}
		
		public function set topBar(value:Container):void {
			if (this._topBar !== value) {
				if (this.appContainer != null) {
					if (this.appContainer.contains(_topBar)) {
						this.appContainer.removeChild(_topBar);
					}
					this.appContainer.addChildAt(value, 0);
				}
				
				this._topBar = value;
			}
		}
		
		private var _bottomBar:Container;
		
		public function get bottomBar():Container {
			return _bottomBar;
		}
		
		public function set bottomBar(value:Container):void {
			if (this._bottomBar !== value) {
				if (this.appContainer != null) {
					if (this.appContainer.contains(_bottomBar)) {
						this.appContainer.removeChild(_bottomBar);
					}
					this.appContainer.addChildAt(value, this.appContainer.getChildren().length);
				}
				
				this._bottomBar = value;
			}
		}
		
		private var _homePageUrl:String;
		
		public function get homePageUrl():String {
			return _homePageUrl;
		}
		
		public function set homePageUrl(value:String):void {
			this._homePageUrl = value;
		}
		
		public function BizMainForm() {
			Alert.yesLabel = "是";
			Alert.okLabel = "确 定"
			Alert.noLabel = "否";
			Alert.cancelLabel = "取 消";
			logger = Log.getLogger(this.className);
			super();
			this.addEventListener(FlexEvent.CREATION_COMPLETE, bizMainUICreateComplete);
			this.percentHeight = 100;
			this.percentWidth = 100;
			BizApplication.instance.mainUI = this;
		}
		
		override protected function createChildren():void {
			super.createChildren();
			
			if (this.needLogin) {
				logger.debug("开始初始化登录界面。");
				loginContainer = new VBox();
				loginContainer.percentHeight = 100;
				loginContainer.percentWidth = 100;
				loginContainer.setStyle("verticalAlign", "middle");
				loginContainer.setStyle("horizontalAlign", "center");
				if (_loginUI != null) {
					loginContainer.addChild(_loginUI as DisplayObject);
					this.addEventListener(LoginUISubmitEvent.LOGIN_SUBMIT, loginUI_SubmitHandler);
				}
				this.addChild(loginContainer);
				logger.debug("增加了登录界面。");	
			}
		}
		
		private function bizMainUICreateComplete(event:FlexEvent):void {
			this.authentication.addEventListener(AuthenticateEvent.Login_Failed, loginFailedHandler); 
			this.authentication.addEventListener(AuthenticateEvent.Login_Success, loginSuccessHandler);
			this.authentication.addEventListener(AuthenticateEvent.Logout_Failed, logoutFailedHandler);
			this.authentication.addEventListener(AuthenticateEvent.Logout_Success, logoutSuccessHandler);
			if (!this.needLogin) {
				this.userAuthenticate(this.authenticationInfo);
			}
		}
		
		private function loginFailed(failedMessage:String):void {
			PopUpProgressBarManager.hide();
			if (this.needLogin) {
				this.loginUI.loginFailed(failedMessage);
			}
		}
		
		private function loginFailedHandler(event:AuthenticateEvent):void {
			this.loginFailed(event.message);
		}
		
		private function loginSuccess():void {
			if (this.needLogin) {
				this.loginContainer.visible = false;
				this.loginContainer.includeInLayout = false;	
			}
			PopUpProgressBarManager.hide();
			this.showAppUI();			
		}
		
		private function loginSuccessHandler(event:AuthenticateEvent):void {
			this.loginSuccess();
		}
		
		private function logoutFailedHandler(event:AuthenticateEvent):void
		{
		}
		
		private function logoutSuccessHandler(event:AuthenticateEvent):void {
			navigateToURL(new URLRequest(Application(Application.application).url.replace("/[[DYNAMIC]]/1", "")), "_self");
		}
		
		override public function initialize():void {
			super.initialize();
		}
		
		private function showLoginUI():void {
			if (this.needLogin) {
				loginContainer.includeInLayout = true;
				loginContainer.visible = true;
				this.loginUI.reset();				
			}
		}
		
		private function showAppUI():void {	
			if (this.appContainer == null) {
				logger.debug("开始初始化主程序界面。");				
				appContainer = new VBox();
				appContainer.percentHeight = 100;
				appContainer.percentWidth = 100;
				appContainer.setStyle("verticalAlign", "middle");
				appContainer.setStyle("horizontalAlign", "center");
				appContainer.setStyle("verticalGap", 0);
				appContainer.setStyle("horizontalGap", 0);
				
				if (this.topBar != null) {
					appContainer.addChild(topBar);
				}
				
				this.dividedBox = new CollapsibleHDividedBox();
				dividedBox.percentHeight = 100;
				dividedBox.percentWidth = 100;
				
				if (navigator != null) {
					navigator.refresh();
					this.addNavigator(navigator);
					dividedBox.addChild(navigatorContainer as DisplayObject);
				}
				
				moduleContainer = new SuperTabNavigator();
				moduleContainer.minTabWidth = 100;
				moduleContainer.percentHeight = 100;
				moduleContainer.width = 100;
				moduleContainer.setStyle("paddingTop", 0);
				moduleContainer.scrollSpeed = 25;
				moduleContainer.closePolicy = SuperTab.CLOSE_ROLLOVER;
				moduleContainer.addEventListener(SuperTabEvent.TAB_CLOSE, moduleContainerTabClose);
				dividedBox.addChild(moduleContainer);
				appContainer.addChild(dividedBox);	
				this.addChild(appContainer);
				
				if (bottomBar != null) {
					appContainer.addChild(bottomBar);
				}
				
				this.showHomePage();
				//			callLater(initNonClosableTab);
				logger.debug("初始化程序主见面结束。");				
			}
			appContainer.includeInLayout = true;
			appContainer.visible = true;
		}
		
		private function moduleContainerTabClose(event:SuperTabEvent):void {
			var tab:VBox = this.moduleContainer.getChildAt(event.tabIndex) as VBox;
			if (tab != null) {
				if (this._viewStatuMap.containsKey(tab.id)) {
					this._viewStatuMap.put(tab.id, false);
				}
				//				this._viewStatuMap.remove(tab.id);
				//				this._viewMap.remove(tab.id);
			}
		}
		
		private function initNonClosableTab():void
		{
			//			moduleContainer.setClosePolicyForTab(0, SuperTab.CLOSE_NEVER);
		}
		
		private function userAuthenticate(authenticationInfo:AuthenticationInfo):void {
			try {
				PopUpProgressBarManager.show("用户验证中...");
				this.authentication.login(authenticationInfo);
			}
			catch(e:Error) {
			}
		}
		
		private function loginUI_SubmitHandler(event:LoginUISubmitEvent):void {
			this.userAuthenticate(event.authenticationInfo);
		}
		
		private function addNavigator(navigator:INavigator):void {
			navigatorContainer = new Panel();
			navigatorContainer.percentHeight = 100;
			navigatorContainer.width = 180;
			navigatorContainer.minWidth= 100;
			navigatorContainer.titleIcon = defaultFunctionsIcon;
			
			navigator.percentHeight = 100;
			navigator.percentWidth = 100;
			navigatorContainer.title = navigator.viewName;
			navigatorContainer.addChild(navigator as DisplayObject);
			navigator.addEventListener(NavigatorItemEvent.NavigatorItem_Click , navigatorSelectionChanged);
			logger.debug("增加了导航器。");
		}
		
		private function addModule(key:String, module:ModuleLoader, title:String):void {
			module.addEventListener(ModuleCommandEvent.ModuleCommand_Raise, moduleCommandRaiseHandler);
			if (module.child is ViewModule) {
				ViewModule(module.child).mainForm = this;
			}
			var viewContainer:VBox = new VBox();
			viewContainer.id = key;
			viewContainer.setStyle("closable", true);
			viewContainer.icon = defaultFunctionIcon;
			viewContainer.label = title;
			viewContainer.percentHeight = 100;
			viewContainer.percentWidth = 100;
			viewContainer.addChild(module);
			moduleContainer.addChild(viewContainer);
			moduleContainer.selectedChild = viewContainer;
			this._viewMap.put(key, module);
			this._viewStatuMap.put(key, true);
		}
		
		public function showModule(moduleUrl:String, moduleTitle:String):void {
			if (StringUtils.isNullOrEmpty(moduleUrl)) {
				return;
			}
			logger.debug("准备通过" + moduleUrl + "读取视图。");
			if (this._viewStatuMap.containsKey(moduleUrl)) {
				var module:ModuleLoader = this._viewMap.get(moduleUrl) as ModuleLoader;
				if (!this._viewStatuMap.get(moduleUrl)) {
					PopUpProgressBarManager.show("\"" + moduleTitle + "\"加载中...", null, 0, 100);
					if (module.child is ViewModule) {
						ViewModule(module.child).refresh();
					}
					this.addModule(moduleUrl, module, moduleTitle);
					PopUpProgressBarManager.hide();
				}
				else {
					var cln:VBox = null;
					var tabCount:int = moduleContainer.getChildren().length;
					for(var i:int = 0;i<tabCount;i++){
						cln = moduleContainer.getChildAt(i) as VBox;
						if(moduleUrl == cln.id){
							this.moduleContainer.selectedChild = cln as Container;
							break;
						}
					}
				}
			}
			else {
				PopUpProgressBarManager.show("\"" + moduleTitle + "\"加载中...", null, 0, 100);
				var moduleLoader:ModuleLoader = new ModuleLoader;
				moduleLoader.percentHeight = 100;
				moduleLoader.percentWidth = 100;
				moduleLoader.addEventListener(ModuleEvent.READY, moduleLoaderReadyHandler);
				moduleLoader.addEventListener(ModuleEvent.PROGRESS, moduleLoaderProgressHandler);
				moduleLoader.addEventListener(ModuleEvent.ERROR, moduleLoaderErrorHandler);
				var moduleInfo:Object = new Object();
				moduleInfo.moduleTitle = moduleTitle;
				moduleLoader.data = moduleInfo;
				moduleLoader.loadModule(moduleUrl);
				moduleLoader.icon = defaultFunctionIcon;
				moduleLoader.setStyle("paddingTop", 5);
				moduleLoader.setStyle("paddingLeft", 5);
				moduleLoader.setStyle("paddingRight", 5);
				moduleLoader.setStyle("paddingBottom", 5);
				this.addModule(moduleUrl, moduleLoader, moduleTitle);
			}
		}
		
		public function hideModule(moduleUrl:String):void {
			if (!StringUtils.isNullOrEmpty(moduleUrl)) {
				if (this._viewStatuMap.containsKey(moduleUrl)) {
					this.moduleContainer.removeChild(this._viewStatuMap.get(moduleUrl) as DisplayObject);	
					this._viewStatuMap.put(moduleUrl, false);
				}
			}
		}
		
		public function hideAllModules():void {
			this.moduleContainer.removeAllChildren();
			for each(var key:String in this._viewStatuMap.keys()) {
				this._viewStatuMap.put(key, false);
			}
		}
		
		public function showHomePage():void {
			this.showModule(this.homePageUrl, "首 页");
		}
		
		private function navigatorSelectionChanged(event:NavigatorItemEvent):void {
			if (!StringUtils.isNullOrEmpty(event.item.link)) {
				this.showModule(event.item.link, event.item.text);
			}
		}
		
		public function init():void{
			Application.application.addChild(this);
		}
		
		//event handler	
		private function moduleLoaderReadyHandler(event:ModuleEvent):void {
//			this.logger.debug("moduleLoader加载模块成功：" + event.relatedObject.name);
			var loader:ModuleLoader = event.currentTarget as ModuleLoader;
			loader.removeEventListener(ModuleEvent.READY, moduleLoaderReadyHandler);
			PopUpProgressBarManager.hide();
		}
		
		private function moduleLoaderProgressHandler(event:ModuleEvent):void {
			PopUpProgressBarManager.show(null, null, event.bytesLoaded, event.bytesTotal);
		}
		
		private function moduleLoaderErrorHandler(event:ModuleEvent):void {
			PopUpProgressBarManager.hide();
			var key:String = event.module.url;
			if (this._viewMap.containsKey(key)) {
				this._viewMap.remove(key);
			}
			
			if (this._viewStatuMap.containsKey(key)) {
				this._viewStatuMap.remove(key);
			}
			Alert.show("加载模块失败。模块连接[" + event.module.url + "]无效。", "错 误");
		}
		
		private function moduleCommandRaiseHandler(event:ModuleCommandEvent):void {
			trace("BizMainForm.moduleCommandRaiseHandler");
			this.dispatchEvent(new ModuleCommandEvent(ModuleCommandEvent.ModuleCommand_Handle, event.commandType));
		}
	}
}